<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <title>通义前问聊天</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/remixicon@2.5.0/fonts/remixicon.css">
    <!-- 添加Marked.js库用于解析Markdown -->
    <script src="https://cdn.jsdelivr.net/npm/marked@4.0.0/marked.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
        }
        
        :root {
            --primary-color: #4361ee;
            --primary-dark: #3a56d4;
            --secondary-color: #7209b7;
            --accent-color: #f72585;
            --bg-color: #f8f9fd;
            --card-bg: #ffffff;
            --text-primary: #2d3748;
            --text-secondary: #4a5568;
            --text-light: #718096;
            --border-color: #e2e8f0;
            --shadow-sm: 0 2px 4px rgba(0,0,0,0.05);
            --shadow-md: 0 4px 6px rgba(0,0,0,0.1);
            --shadow-lg: 0 10px 15px rgba(0,0,0,0.1);
            --radius-sm: 6px;
            --radius-md: 10px;
            --radius-lg: 16px;
            --transition: all 0.3s ease;
        }
        
        body {
            background-color: var(--bg-color);
            color: var(--text-primary);
            line-height: 1.6;
            height: 100vh;
            overflow: hidden;
        }
        
        .app-container {
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }
        
        .app-header {
            text-align: center;
            margin-bottom: 25px;
            padding-bottom: 15px;
            position: relative;
        }
        
        .app-header::after {
            content: "";
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 60px;
            height: 3px;
            background: linear-gradient(90deg, var(--primary-color), var(--secondary-color));
            border-radius: 3px;
        }
        
        .app-title {
            color: var(--primary-color);
            font-size: 32px;
            font-weight: bold;
            letter-spacing: -0.5px;
        }
        
        .app-subtitle {
            color: var(--text-light);
            font-size: 14px;
            margin-top: 5px;
        }
        
        .controls {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
        }
        
        .button {
            padding: 10px 18px;
            border: none;
            border-radius: var(--radius-sm);
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            transition: var(--transition);
            display: flex;
            align-items: center;
            gap: 6px;
        }
        
        .button i {
            font-size: 1.2em;
        }
        
        .button-primary {
            background-color: var(--primary-color);
            color: white;
            box-shadow: var(--shadow-sm);
        }
        
        .button-primary:hover {
            background-color: var(--primary-dark);
            box-shadow: var(--shadow-md);
            transform: translateY(-2px);
        }
        
        .chat-container {
            flex: 1;
            background-color: var(--card-bg);
            border-radius: var(--radius-lg);
            box-shadow: var(--shadow-lg);
            display: flex;
            flex-direction: column;
            overflow: hidden;
            position: relative;
            transition: var(--transition);
        }
        
        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            scroll-behavior: smooth;
        }
        
        .chat-messages::-webkit-scrollbar {
            width: 6px;
        }
        
        .chat-messages::-webkit-scrollbar-track {
            background: var(--border-color);
            border-radius: 10px;
        }
        
        .chat-messages::-webkit-scrollbar-thumb {
            background: var(--text-light);
            border-radius: 10px;
        }
        
        .message {
            margin-bottom: 24px;
            display: flex;
            flex-direction: column;
            animation: fadeIn 0.3s ease;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .message-content {
            padding: 14px 18px;
            border-radius: var(--radius-md);
            max-width: 80%;
            word-wrap: break-word;
            box-shadow: var(--shadow-sm);
            position: relative;
            line-height: 1.5;
        }
        
        .user-message {
            align-items: flex-end;
        }
        
        .user-message .message-content {
            background: linear-gradient(120deg, var(--primary-color), var(--secondary-color));
            color: white;
            border-bottom-right-radius: 0;
        }
        
        .user-message .message-content::after {
            content: "";
            position: absolute;
            bottom: 0;
            right: -8px;
            width: 0;
            height: 0;
            border-left: 10px solid var(--secondary-color);
            border-top: 0 solid transparent;
            border-bottom: 10px solid transparent;
        }
        
        .ai-message {
            align-items: flex-start;
        }
        
        .ai-message .message-content {
            background-color: #f5f7ff;
            color: var(--text-primary);
            border-bottom-left-radius: 0;
            border-left: 3px solid var(--primary-color);
        }
        
        .ai-message .message-content code {
            background-color: rgba(0, 0, 0, 0.05);
            padding: 2px 4px;
            border-radius: 3px;
            font-family: Consolas, Monaco, 'Andale Mono', monospace;
            font-size: 0.9em;
        }
        
        .ai-message .message-content pre {
            background-color: #f1f3f5;
            padding: 12px;
            border-radius: 5px;
            overflow-x: auto;
            margin: 10px 0;
            border: 1px solid var(--border-color);
        }
        
        .ai-message .message-content pre code {
            background-color: transparent;
            padding: 0;
            display: block;
            line-height: 1.5;
        }
        
        .ai-message .message-content p {
            margin: 8px 0;
        }
        
        .ai-message .message-content ul, 
        .ai-message .message-content ol {
            margin: 8px 0;
            padding-left: 24px;
        }
        
        .ai-message .message-content li {
            margin-bottom: 4px;
        }
        
        .ai-message .message-content h1, 
        .ai-message .message-content h2, 
        .ai-message .message-content h3, 
        .ai-message .message-content h4, 
        .ai-message .message-content h5, 
        .ai-message .message-content h6 {
            margin: 16px 0 8px 0;
            color: var(--text-primary);
            font-weight: 600;
        }
        
        .ai-message .message-content h1 { font-size: 1.5em; }
        .ai-message .message-content h2 { font-size: 1.3em; }
        .ai-message .message-content h3 { font-size: 1.1em; }
        
        .ai-message .message-content blockquote {
            border-left: 3px solid var(--primary-color);
            padding: 10px 15px;
            margin: 10px 0;
            color: var(--text-secondary);
            background-color: rgba(67, 97, 238, 0.05);
            border-radius: 0 5px 5px 0;
        }
        
        .ai-message .message-content a {
            color: var(--primary-color);
            text-decoration: none;
        }
        
        .ai-message .message-content a:hover {
            text-decoration: underline;
        }
        
        .ai-message .message-content table {
            border-collapse: collapse;
            width: 100%;
            margin: 12px 0;
        }
        
        .ai-message .message-content th, 
        .ai-message .message-content td {
            border: 1px solid var(--border-color);
            padding: 6px 10px;
            text-align: left;
        }
        
        .ai-message .message-content th {
            background-color: rgba(67, 97, 238, 0.05);
            font-weight: 600;
        }
        
        .ai-message .message-content::after {
            content: "";
            position: absolute;
            bottom: 0;
            left: -8px;
            width: 0;
            height: 0;
            border-right: 10px solid #f5f7ff;
            border-top: 0 solid transparent;
            border-bottom: 10px solid transparent;
        }
        
        .system-message {
            align-items: center;
        }
        
        .system-message .message-content {
            background-color: #f0f4ff;
            color: var(--text-light);
            font-style: italic;
            font-size: 14px;
            border-left: 3px solid #a0aec0;
            max-width: 70%;
        }
        
        .message-meta {
            font-size: 12px;
            color: var(--text-light);
            margin-top: 6px;
            margin-left: 8px;
            margin-right: 8px;
            display: flex;
            align-items: center;
            gap: 4px;
        }
        
        .message-meta i {
            font-size: 14px;
        }
        
        .chat-input {
            display: flex;
            align-items: center;
            border-top: 1px solid var(--border-color);
            padding: 15px 20px;
            background-color: #f9fafc;
            position: relative;
        }
        
        .chat-input::before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 1px;
            background: linear-gradient(90deg, transparent, var(--border-color), transparent);
        }
        
        .input-field {
            flex: 1;
            padding: 12px 15px;
            border: 1px solid var(--border-color);
            border-radius: var(--radius-md);
            font-size: 14px;
            outline: none;
            resize: none;
            height: 45px;
            max-height: 120px;
            transition: var(--transition);
            box-shadow: var(--shadow-sm);
        }
        
        .input-field:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.1);
        }
        
        .send-button {
            margin-left: 10px;
            width: 45px;
            height: 45px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 50%;
            cursor: pointer;
            font-size: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: var(--transition);
            box-shadow: var(--shadow-sm);
        }
        
        .send-button:hover {
            background-color: var(--primary-dark);
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }
        
        .send-button:disabled {
            background-color: var(--text-light);
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        
        .typing-indicator {
            display: inline-flex;
            align-items: center;
            padding: 8px 15px;
            background-color: #f5f7ff;
            border-radius: 20px;
            font-size: 14px;
            color: var(--text-light);
            margin-bottom: 15px;
            box-shadow: var(--shadow-sm);
        }
        
        .typing-animation {
            display: inline-flex;
            margin-left: 6px;
        }
        
        .typing-dot {
            display: inline-block;
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background-color: var(--primary-color);
            margin-right: 3px;
            animation: typing-dot 1.4s infinite ease-in-out both;
        }
        
        .typing-dot:nth-child(1) {
            animation-delay: 0s;
        }
        
        .typing-dot:nth-child(2) {
            animation-delay: 0.2s;
        }
        
        .typing-dot:nth-child(3) {
            animation-delay: 0.4s;
            margin-right: 0;
        }
        
        .nav-links {
            display: flex;
            justify-content: center;
            margin-bottom: 20px;
            gap: 10px;
        }
        
        .nav-link {
            text-decoration: none;
            padding: 8px 16px;
            color: var(--text-primary);
            font-weight: 600;
            border-radius: var(--radius-sm);
            transition: var(--transition);
            display: flex;
            align-items: center;
            gap: 6px;
        }
        
        .nav-link:hover {
            background-color: rgba(67, 97, 238, 0.1);
            color: var(--primary-color);
            transform: translateY(-2px);
        }
        
        .nav-link i {
            font-size: 1.2em;
        }
        
        /* 思考功能样式 */
        .thinking-toggle {
            display: flex;
            align-items: center;
            margin-right: 10px;
            cursor: pointer;
            user-select: none;
        }
        
        .toggle-switch {
            position: relative;
            display: inline-block;
            width: 48px;
            height: 24px;
            margin-right: 10px;
        }
        
        .toggle-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        
        .toggle-slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: var(--text-light);
            transition: .4s;
            border-radius: 24px;
        }
        
        .toggle-slider:before {
            position: absolute;
            content: "";
            height: 18px;
            width: 18px;
            left: 3px;
            bottom: 3px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
            box-shadow: var(--shadow-sm);
        }
        
        input:checked + .toggle-slider {
            background: linear-gradient(90deg, var(--primary-color), var(--secondary-color));
        }
        
        input:checked + .toggle-slider:before {
            transform: translateX(24px);
        }
        
        .thinking-section {
            background-color: #f8f9fa;
            border-radius: var(--radius-md);
            padding: 15px 18px;
            margin-bottom: 15px;
            border-left: 4px solid var(--secondary-color);
            font-size: 14px;
            color: var(--text-secondary);
            display: none;
            box-shadow: var(--shadow-sm);
            animation: fadeIn 0.5s ease;
            overflow-wrap: break-word;
            white-space: pre-line;  /* 保留换行符 */
        }
        
        .thinking-title {
            font-weight: bold;
            margin-bottom: 12px;
            color: var(--secondary-color);
            display: flex;
            align-items: center;
            gap: 6px;
        }
        
        /* Markdown内容样式 */
        .thinking-content {
            line-height: 1.7;
            white-space: normal;
        }
        
        .thinking-content code {
            background-color: rgba(0, 0, 0, 0.05);
            padding: 2px 4px;
            border-radius: 3px;
            font-family: Consolas, Monaco, 'Andale Mono', monospace;
            font-size: 0.9em;
        }
        
        .thinking-content pre {
            background-color: #f1f3f5;
            padding: 12px;
            border-radius: 5px;
            overflow-x: auto;
            margin: 10px 0;
            border: 1px solid var(--border-color);
        }
        
        .thinking-content pre code {
            background-color: transparent;
            padding: 0;
            display: block;
            line-height: 1.5;
        }
        
        .thinking-content p {
            margin: 10px 0;
        }
        
        .thinking-content ul, .thinking-content ol {
            margin: 10px 0;
            padding-left: 24px;
        }
        
        .thinking-content li {
            margin-bottom: 6px;
        }
        
        .thinking-content h1, .thinking-content h2, .thinking-content h3, 
        .thinking-content h4, .thinking-content h5, .thinking-content h6 {
            margin: 18px 0 10px 0;
            color: var(--text-primary);
            font-weight: 600;
        }
        
        .thinking-content h1 { font-size: 1.6em; }
        .thinking-content h2 { font-size: 1.4em; }
        .thinking-content h3 { font-size: 1.2em; }
        
        .thinking-content blockquote {
            border-left: 3px solid var(--primary-color);
            padding: 12px 15px;
            margin: 12px 0;
            color: var(--text-secondary);
            background-color: rgba(67, 97, 238, 0.05);
            border-radius: 0 5px 5px 0;
        }
        
        .thinking-content a {
            color: var(--primary-color);
            text-decoration: none;
        }
        
        .thinking-content a:hover {
            text-decoration: underline;
        }
        
        .thinking-content table {
            border-collapse: collapse;
            width: 100%;
            margin: 15px 0;
        }
        
        .thinking-content th, .thinking-content td {
            border: 1px solid var(--border-color);
            padding: 8px 12px;
            text-align: left;
        }
        
        .thinking-content th {
            background-color: rgba(67, 97, 238, 0.05);
            font-weight: 600;
        }
        
        /* 突出显示小标题或编号 */
        .thinking-content strong {
            color: var(--primary-color);
            font-weight: 600;
        }
        
        /* 增加间距和可读性 */
        .thinking-content br + br {
            display: block;
            content: "";
            margin-top: 8px;
        }
        
        @keyframes typing-dot {
            0%, 80%, 100% { 
                transform: scale(0.7); 
                opacity: 0.5;
            }
            40% { 
                transform: scale(1); 
                opacity: 1;
            }
        }
        
        @media (max-width: 768px) {
            .app-container {
                padding: 10px;
                height: 100vh;
            }
            
            .message-content {
                max-width: 90%;
            }
            
            .app-title {
                font-size: 24px;
            }
            
            .nav-links {
                flex-wrap: wrap;
            }
            
            .thinking-toggle span {
                display: none;
            }
        }
        
        /* 添加发送按钮具体文字 */
        .send-button i {
            font-size: 1.2em;
            color: white;
        }
        
        /* 添加一个上下文记忆指示器 */
        .memory-indicator {
            position: absolute;
            bottom: 70px;
            right: 20px;
            background: rgba(67, 97, 238, 0.1);
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 12px;
            color: var(--primary-color);
            display: flex;
            align-items: center;
            gap: 5px;
            box-shadow: var(--shadow-sm);
            z-index: 10;
            transition: opacity 0.3s ease;
        }
        
        .memory-indicator.hidden {
            opacity: 0;
            pointer-events: none;
        }
    </style>
</head>
<body>
    <div class="app-container">
        <div class="app-header">
            <h1 class="app-title">通义前问聊天</h1>
            <p class="app-subtitle">由阿里云通义大模型驱动</p>
        </div>
        
        <div class="nav-links">
            <a href="knowledge.html" class="nav-link">
                <i class="ri-book-2-line"></i>
                知识库管理
            </a>
            <a href="excel_upload.html" class="nav-link">
                <i class="ri-file-excel-2-line"></i>
                Excel向量化
            </a>
        </div>
        
        <div class="controls">
            <button id="new-conversation" class="button button-primary">
                <i class="ri-refresh-line"></i>
                清空对话
            </button>
            <div class="thinking-toggle">
                <label class="toggle-switch">
                    <input type="checkbox" id="thinking-toggle">
                    <span class="toggle-slider"></span>
                </label>
                <span>显示思考过程</span>
            </div>
        </div>
        
        <div class="chat-container">
            <div id="chat-messages" class="chat-messages"></div>
            
            <div class="memory-indicator hidden" id="memory-indicator">
                <i class="ri-brain-line"></i> 
                <span>已保存<span id="message-count">0</span>条对话记录</span>
            </div>
            
            <div class="chat-input">
                <textarea id="message-input" class="input-field" placeholder="输入您的问题..." rows="1"></textarea>
                <button id="send-button" class="send-button">
                    <i class="ri-send-plane-fill"></i>
                </button>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let isWaitingForResponse = false;
        let isThinkingEnabled = false;
        let conversationHistory = []; // 存储对话历史
        let maxHistoryLength = 10; // 最大记忆条数
        
        // DOM 元素
        const chatMessages = document.getElementById('chat-messages');
        const messageInput = document.getElementById('message-input');
        const sendButton = document.getElementById('send-button');
        const newConversationButton = document.getElementById('new-conversation');
        const thinkingToggle = document.getElementById('thinking-toggle');
        const memoryIndicator = document.getElementById('memory-indicator');
        const messageCountElement = document.getElementById('message-count');
        
        // 自动调整输入框高度
        messageInput.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = (this.scrollHeight < 120) ? this.scrollHeight + 'px' : '120px';
        });
        
        // 事件监听器
        newConversationButton.addEventListener('click', clearConversation);
        sendButton.addEventListener('click', handleSendMessage);
        thinkingToggle.addEventListener('change', function() {
            isThinkingEnabled = this.checked;
        });
        
        messageInput.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                handleSendMessage();
            }
        });
        
        // 更新记忆指示器
        function updateMemoryIndicator() {
            if (conversationHistory.length > 0) {
                messageCountElement.textContent = conversationHistory.length;
                memoryIndicator.classList.remove('hidden');
            } else {
                memoryIndicator.classList.add('hidden');
            }
        }
        
        // 清空对话
        function clearConversation() {
            // 添加简单的动画效果
            chatMessages.style.opacity = '0';
            setTimeout(() => {
                clearChatMessages();
                conversationHistory = []; // 清空对话历史
                updateMemoryIndicator();
                addSystemMessage("对话已清空，您可以开始新的对话");
                chatMessages.style.opacity = '1';
            }, 300);
        }
        
        // 处理发送消息
        function handleSendMessage() {
            const message = messageInput.value.trim();
            
            if (!message || isWaitingForResponse) return;
            
            sendMessage(message);
            
            messageInput.value = '';
            messageInput.style.height = '45px';
            messageInput.focus(); // 将焦点重新放回输入框
        }
        
        // 发送消息
        function sendMessage(message) {
            addUserMessage(message);
            setWaitingState(true);
            
            // 将用户消息添加到历史记录
            conversationHistory.push({role: "user", content: message});
            
            // 限制历史记录长度
            if (conversationHistory.length > maxHistoryLength * 2) { // *2 是因为每次对话包含用户和AI各一条
                conversationHistory = conversationHistory.slice(-maxHistoryLength * 2);
            }
            
            updateMemoryIndicator();
            
            if (isThinkingEnabled) {
                // 先获取思考过程，再获取回答
                sendStreamingThinking(message);
            } else {
                // 直接获取回答
                sendStreamingMessage(message);
            }
        }
        
        // 发送思考请求
        function sendStreamingThinking(message) {
            // 创建思考容器
            const aiMessageElement = document.createElement('div');
            aiMessageElement.className = 'message ai-message';
            
            // 思考部分
            const thinkingSection = document.createElement('div');
            thinkingSection.className = 'thinking-section';
            thinkingSection.style.display = 'block';
            
            const thinkingTitle = document.createElement('div');
            thinkingTitle.className = 'thinking-title';
            thinkingTitle.innerHTML = '<i class="ri-brain-line"></i> 思考过程';
            
            const thinkingContent = document.createElement('div');
            thinkingContent.className = 'thinking-content';
            
            const typingIndicator = createTypingIndicator();
            thinkingContent.appendChild(typingIndicator);
            
            thinkingSection.appendChild(thinkingTitle);
            thinkingSection.appendChild(thinkingContent);
            
            // 回答部分
            const contentElement = document.createElement('div');
            contentElement.className = 'message-content';
            contentElement.textContent = '思考中...';
            
            aiMessageElement.appendChild(thinkingSection);
            aiMessageElement.appendChild(contentElement);
            chatMessages.appendChild(aiMessageElement);
            
            scrollToBottom();
            
            // 构建查询参数，包含历史记录
            const params = new URLSearchParams();
            params.append('message', message);
            
            // 添加历史记录
            if (conversationHistory.length > 1) { // 至少需要有一条历史记录(排除当前消息)
                params.append('history', JSON.stringify(conversationHistory.slice(0, -1)));
            }
            
            // 请求思考流
            const thinkingSource = new EventSource(`/thinking?${params.toString()}`);
            
            let fullThinking = '';
            let firstThinkingChunk = true;
            
            thinkingSource.onmessage = function(event) {
                if (firstThinkingChunk) {
                    thinkingContent.innerHTML = '';
                    firstThinkingChunk = false;
                }
                
                try {
                    fullThinking += event.data;
                    
                    // 预处理Markdown文本，特别优化中文内容格式
                    let processedMarkdown = fullThinking
                        // 处理以###开头的标题 (常见于LLM输出)
                        .replace(/^(#{1,6})([^#\s])/gm, '$1 $2')
                        // 单独处理数字+点+中文标题的格式 (如 "4.多角度分析")
                        .replace(/^(\d+)\.([^\s\d])/gm, '$1. $2')
                        // 处理中文数字标题 (如 "2. 思考框架")
                        .replace(/^(\d+)\.\s+([\u4e00-\u9fa5]{2,}.*?)$/gm, '\n\n## $1. $2\n\n')
                        // 处理无序列表项 (以•、*或-开头)
                        .replace(/^(\s*)([•\*\-])([^\s])/gm, '$1$2 $3')
                        // 处理有序列表项 (数字+点开头)
                        .replace(/^(\s*)(\d+\.)([^\s])/gm, '$1$2 $3')
                        // 确保列表项之间有换行
                        .replace(/([\n\r])([•\*\-]|\d+\.)\s/g, '$1\n$2 ')
                        // 在句号等中文标点后添加换行，便于分段
                        .replace(/([。！？\n])\s*([\u4e00-\u9fa5])/g, '$1\n\n$2');
                    
                    // marked配置选项
                    const markedOptions = {
                        breaks: true,        // 将单行换行转换为<br>
                        gfm: true,           // 启用GitHub风格的Markdown
                        headerIds: false,    // 禁用自动为标题添加ID
                        mangle: false,       // 不转义HTML实体
                        sanitize: false,     // 允许HTML标签通过
                        smartLists: true,    // 使用更智能的列表识别
                    };
                    
                    // 解析Markdown为HTML
                    const parsedHtml = marked.parse(processedMarkdown, markedOptions);
                    
                    // 应用HTML到内容元素
                    thinkingContent.innerHTML = parsedHtml;
                    
                    // 确保思考部分显示
                    thinkingSection.style.display = 'block';
                } catch (error) {
                    console.error("解析Markdown失败:", error);
                    // 降级处理 - 如果解析失败则使用纯文本显示
                    thinkingContent.textContent = fullThinking;
                    thinkingSection.style.display = 'block';
                }
                
                scrollToBottom();
            };
            
            thinkingSource.onerror = function() {
                thinkingSource.close();
                
                // 思考完成后，请求回答
                contentElement.textContent = '生成回答中...';
                requestAnswer(message, contentElement, aiMessageElement);
            };
        }
        
        // 请求最终答案
        function requestAnswer(message, contentElement, aiMessageElement) {
            // 构建查询参数，包含历史记录
            const params = new URLSearchParams();
            params.append('message', message);
            
            // 添加历史记录
            if (conversationHistory.length > 1) { // 至少需要有一条历史记录(排除当前消息)
                params.append('history', JSON.stringify(conversationHistory.slice(0, -1)));
            }
            
            const eventSource = new EventSource(`/chat?${params.toString()}`);
            
            let fullResponse = '';
            let firstChunk = true;
            
            eventSource.onmessage = function(event) {
                if (firstChunk) {
                    contentElement.innerHTML = '';
                    firstChunk = false;
                }
                
                try {
                    fullResponse += event.data;
                    
                    // 尝试解析Markdown（如果回答包含Markdown格式）
                    const markedOptions = {
                        breaks: true,
                        gfm: true
                    };
                    
                    // 检查内容是否可能包含Markdown
                    const potentialMarkdown = /(\*\*|__|\*|_|##|#|`|\[.*\]\(.*\)|>|\d\.|-)/.test(fullResponse);
                    
                    if (potentialMarkdown) {
                        // 内容可能包含Markdown格式，使用marked解析
                        contentElement.innerHTML = marked.parse(fullResponse, markedOptions);
                    } else {
                        // 纯文本显示
                        contentElement.textContent = fullResponse;
                    }
                    
                    scrollToBottom();
                } catch (error) {
                    console.error("解析回答失败:", error);
                    // 降级为纯文本
                    contentElement.textContent = fullResponse;
                    scrollToBottom();
                }
            };
            
            eventSource.onerror = function(error) {
                eventSource.close();
                if (firstChunk) {
                    contentElement.innerHTML = '';
                    contentElement.textContent = '接收响应时出错';
                } else {
                    // 将AI响应添加到历史记录
                    conversationHistory.push({role: "assistant", content: fullResponse});
                    updateMemoryIndicator();
                }
                
                // 添加时间标记
                const timeElement = document.createElement('div');
                timeElement.className = 'message-meta';
                timeElement.innerHTML = `<i class="ri-time-line"></i> ${getCurrentTime()}`;
                aiMessageElement.appendChild(timeElement);
                
                setWaitingState(false);
            };
        }
        
        // 发送流式消息（不显示思考过程）
        function sendStreamingMessage(message) {
            const aiMessageElement = document.createElement('div');
            aiMessageElement.className = 'message ai-message';
            
            const contentElement = document.createElement('div');
            contentElement.className = 'message-content';
            
            const typingIndicator = createTypingIndicator();
            contentElement.appendChild(typingIndicator);
            
            aiMessageElement.appendChild(contentElement);
            chatMessages.appendChild(aiMessageElement);
            
            scrollToBottom();
            
            // 构建查询参数，包含历史记录
            const params = new URLSearchParams();
            params.append('message', message);
            
            // 添加历史记录
            if (conversationHistory.length > 1) { // 至少需要有一条历史记录(排除当前消息)
                params.append('history', JSON.stringify(conversationHistory.slice(0, -1)));
            }
            
            const eventSource = new EventSource(`/chat?${params.toString()}`);
            
            let fullResponse = '';
            let firstChunk = true;
            
            eventSource.onmessage = function(event) {
                if (firstChunk) {
                    contentElement.innerHTML = '';
                    firstChunk = false;
                }
                
                try {
                    fullResponse += event.data;
                    
                    // 尝试解析Markdown（如果回答包含Markdown格式）
                    const markedOptions = {
                        breaks: true,
                        gfm: true
                    };
                    
                    // 检查内容是否可能包含Markdown
                    const potentialMarkdown = /(\*\*|__|\*|_|##|#|`|\[.*\]\(.*\)|>|\d\.|-)/.test(fullResponse);
                    
                    if (potentialMarkdown) {
                        // 内容可能包含Markdown格式，使用marked解析
                        contentElement.innerHTML = marked.parse(fullResponse, markedOptions);
                    } else {
                        // 纯文本显示
                        contentElement.textContent = fullResponse;
                    }
                    
                    scrollToBottom();
                } catch (error) {
                    console.error("解析回答失败:", error);
                    // 降级为纯文本
                    contentElement.textContent = fullResponse;
                    scrollToBottom();
                }
            };
            
            eventSource.onerror = function(error) {
                eventSource.close();
                if (firstChunk) {
                    contentElement.innerHTML = '';
                    contentElement.textContent = '接收响应时出错';
                } else {
                    // 将AI响应添加到历史记录
                    conversationHistory.push({role: "assistant", content: fullResponse});
                    updateMemoryIndicator();
                }
                
                // 添加时间标记
                const timeElement = document.createElement('div');
                timeElement.className = 'message-meta';
                timeElement.innerHTML = `<i class="ri-time-line"></i> ${getCurrentTime()}`;
                aiMessageElement.appendChild(timeElement);
                
                setWaitingState(false);
            };
        }
        
        // 添加用户消息
        function addUserMessage(message) {
            const messageElement = document.createElement('div');
            messageElement.className = 'message user-message';
            
            const contentElement = document.createElement('div');
            contentElement.className = 'message-content';
            contentElement.textContent = message;
            
            const timeElement = document.createElement('div');
            timeElement.className = 'message-meta';
            timeElement.innerHTML = `<i class="ri-time-line"></i> ${getCurrentTime()}`;
            
            messageElement.appendChild(contentElement);
            messageElement.appendChild(timeElement);
            
            chatMessages.appendChild(messageElement);
            scrollToBottom();
        }
        
        // 添加AI消息
        function addAiMessage(message) {
            const messageElement = document.createElement('div');
            messageElement.className = 'message ai-message';
            
            const contentElement = document.createElement('div');
            contentElement.className = 'message-content';
            contentElement.textContent = message;
            
            const timeElement = document.createElement('div');
            timeElement.className = 'message-meta';
            timeElement.innerHTML = `<i class="ri-time-line"></i> ${getCurrentTime()}`;
            
            messageElement.appendChild(contentElement);
            messageElement.appendChild(timeElement);
            
            chatMessages.appendChild(messageElement);
            scrollToBottom();
        }
        
        // 添加系统消息
        function addSystemMessage(message) {
            const messageElement = document.createElement('div');
            messageElement.className = 'message system-message';
            
            const contentElement = document.createElement('div');
            contentElement.className = 'message-content';
            contentElement.innerHTML = `<i class="ri-information-line"></i> ${message}`;
            
            messageElement.appendChild(contentElement);
            chatMessages.appendChild(messageElement);
            scrollToBottom();
        }
        
        // 创建正在输入的指示器
        function createTypingIndicator() {
            const indicator = document.createElement('div');
            indicator.className = 'typing-indicator';
            indicator.innerHTML = '正在生成';
            
            const animation = document.createElement('div');
            animation.className = 'typing-animation';
            
            for (let i = 0; i < 3; i++) {
                const dot = document.createElement('span');
                dot.className = 'typing-dot';
                animation.appendChild(dot);
            }
            
            indicator.appendChild(animation);
            return indicator;
        }
        
        // 清空聊天区域
        function clearChatMessages() {
            chatMessages.innerHTML = '';
        }
        
        // 滚动到底部
        function scrollToBottom() {
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }
        
        // 获取当前时间
        function getCurrentTime() {
            const now = new Date();
            return now.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
        }
        
        // 设置等待状态
        function setWaitingState(isWaiting) {
            isWaitingForResponse = isWaiting;
            sendButton.disabled = isWaiting;
            messageInput.disabled = isWaiting;
            
            if (!isWaiting) {
                // 当响应结束时，重新聚焦输入框
                setTimeout(() => {
                    messageInput.focus();
                }, 100);
            }
        }
        
        // 页面加载时欢迎消息
        window.addEventListener('DOMContentLoaded', function() {
            setTimeout(() => {
                addSystemMessage("欢迎使用通义前问聊天，请输入您的问题");
                // 初始状态下聚焦输入框
                messageInput.focus();
            }, 300);
        });
    </script>
</body>
</html>